package com.lagou;

// Druid 连接池工具类
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class DruidUtils {

    // private static DataSource dataSource;

    // static Logger logger = LoggerFactory.getLogger(DruidUtils.class);
/**
 * 获取zk节点中的数据库配置信息并加载配置信息
 * @param path zk节点路径
 * @param zkClient zk客户端连接
 */

    public static DataSource addConf (ZkClient zkClient, String path) {

        String dbConfig = zkClient.readData(path);
        String url = dbConfig.split("\t")[0];
        String username = dbConfig.split("\t")[1];
        String password = dbConfig.split("\t")[2];

        System.out.println("dbConfig from zk is " +dbConfig);
        System.out.println("url = " + url);
        System.out.println("username = " + username);
        System.out.println("password = " + password);

        DataSource dataSource = null;
        try {
            Map<String, String> dbConfigMap = new HashMap<>();
            dbConfigMap.put("url",url);
            dbConfigMap.put("username",username);
            dbConfigMap.put("password",password);
           dataSource = DruidDataSourceFactory.createDataSource(dbConfigMap);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return dataSource;
    }

    // 获取连接
    public static Connection getConnection(DataSource dataSource) {
        try {
            return  dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 释放资源
    public static void close(Connection con, Statement statement, ResultSet resultSet) {
        if (con != null && statement != null && resultSet != null) {
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 执行查看数据库中所有表数据的查询
     *     @param zkPath zk数据库连接信息
     *     @param dataSource druid连接
     */
    public static void execQuery(DataSource dataSource,String zkPath) {
        //DruidUtils.addConf(zkClient, zkPath)
        Connection con = DruidUtils.getConnection(dataSource);
        Statement statement = null;
        ResultSet re = null;
        try {
            statement = con.createStatement();
            re = statement.executeQuery("show tables");
            while (re.next()) {
                System.out.println(re.getString(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        DruidUtils.close(con,statement,re);
    }
}
